import { http } from "@/utils/http";

export type Permission = {
  id: number;
  name: string;
  code: string;
  description?: string;
  parent_id?: number;
  status: number;
  created_at: string;
  updated_at: string;
  deleted_at?: string;
  children?: Permission[];
};

export type PermissionResponse = {
  success: boolean;
  code: number;
  message: string;
  data: Permission;
};

export type PermissionListResponse = {
  success: boolean;
  code: number;
  message: string;
  data: Permission[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_page: number;
  };
};

export type PaginationParams = {
  page?: number;
  page_size?: number;
};

/** 创建权限 */
export const createPermission = (data: Partial<Permission>) => {
  return http.request<PermissionResponse>("post", "/permission", { data });
};

/** 获取权限列表 */
export const getPermissions = (params?: PaginationParams) => {
  return http.request<PermissionListResponse>("get", "/permission", { params });
};

/** 获取权限树 */
export const getPermissionsTree = () => {
  return http.request<PermissionListResponse>("get", "/permission/tree");
};

/** 获取权限详情 */
export const getPermissionById = (id: number) => {
  return http.request<PermissionResponse>("get", `/permission/${id}`);
};

/** 根据code获取权限 */
export const getPermissionByCode = (code: string) => {
  return http.request<PermissionResponse>("get", `/permission/code/${code}`);
};

/** 更新权限 */
export const updatePermission = (id: number, data: Partial<Permission>) => {
  return http.request<PermissionResponse>("put", `/permission/${id}`, { data });
};

/** 删除权限 */
export const deletePermission = (id: number) => {
  return http.request("delete", `/permission/${id}`);
};

/** 获取角色的权限 */
export const getPermissionsByRoleId = (id: number) => {
  return http.request<PermissionListResponse>("get", `/permission/role/${id}`);
};

/** 获取拥有指定权限的角色 */
export const getRolesByPermissionId = (id: number, params?: PaginationParams) => {
  return http.request<RoleListResponse>("get", `/permission/permission/${id}/roles`, { params });
};

/** 获取管理员的权限 */
export const getPermissionsByAdminId = (id: number) => {
  return http.request<PermissionListResponse>("get", `/permission/admin/${id}`);
};

/** 为角色分配权限 */
export const assignPermissionToRole = (role_id: number, permission_id: number) => {
  return http.request("post", "/permission/assign", { params: { role_id, permission_id } });
};

/** 从角色移除权限 */
export const removePermissionFromRole = (role_id: number, permission_id: number) => {
  return http.request("delete", "/permission/remove", { params: { role_id, permission_id } });
};